<?php

    class Files_Controller extends Application {

        function setup()
        {
            $this->actions = array('index','add','delete','file_types','delete_file_type',
                                   'browse','crop_image','modify');
            $this->use_layout('admin_layout.php');
            $this->before_filter('is_logged_in');
            $this->before_filter('has_access');
            use_model('files','file_folders','file_types');
			
			/// set subnav to template
			$subnav = array(); 		
			$subnav['View Files'] = array('controller'=>'admin/files');
			if (has_access_to('Files::Modify File Types')) { 		
				$subnav['Modify File Types'] = array('controller'=>'admin/files' ,'action'=>'file_types');
			}
			$this->assign('subnav',$subnav);
        }
        
        function has_access()
        {
            if (!has_access_to('Files::Access Files')) {
                flash('error','Sorry but you do not have access to the Files tool');
                $this->redirect_to(array('controller'=>'admin/dashboard'));
             }
        }
        
		function index() 
		{
		    $files =& new Files();
		    $this->assign_ref('files',$files);
		    
		    $folders =& new File_Folders();
		    $this->assign_ref('folders',$folders);		 
		    
		    // type filters
		    if ( isset($_REQUEST['files_filter_by']) )
		    {
		        $_SESSION['files_filter_by'] = htmlspecialchars($_REQUEST['files_filter_by']);
		    }
		    
		    if ( empty($_SESSION['files_filter_by']) )
		    {
		        $_SESSION['files_filter_by'] = 'all';
		    }
		    
		    $this->assign('file_filters',$files->get_filters());
		    $this->assign('file_filter_selected', $_SESSION['files_filter_by']);   		    
		    
		    // get all folders
		    $file_folder_id = isset($_REQUEST['file_folder_id']) ? (int) $_REQUEST['file_folder_id'] 
		                                                         : 1 ;
		    $this->assign('file_folder_id',$file_folder_id);
		    $this->assign('all_files', $files->get_files_by_folder($file_folder_id, 
		                                                          $_SESSION['files_filter_by']));
		    $this->assign('all_folders', $folders->get_sub_folders($file_folder_id));
		    $this->assign('folder_path',$folders->get_breadcrumb($file_folder_id));
		    $this->assign('redirect','index');
		    		    
		}
		
		function browse() 
		{
			// kill assigned subnav
			unset($this->tpl_vars['subnav']);
			
		    $this->use_layout('filebrowser_layout.php');
		    $files =& new Files();
		    $this->assign_ref('files',$files);
		    
		    $folders =& new File_Folders();
		    $this->assign_ref('folders',$folders);	
		    
		    // type filters
		    if ( isset($_REQUEST['files_filter_by']) )
		    {
		        $_SESSION['files_filter_by'] = htmlspecialchars($_REQUEST['files_filter_by']);
		    }
		    
		    if ( empty($_SESSION['files_filter_by']) )
		    {
		        $_SESSION['files_filter_by'] = 'all';
		    }
		    
		    $this->assign('file_filters',$files->get_filters());
		    $this->assign('file_filter_selected', $_SESSION['files_filter_by']);	    		    
		    
		    // get all folders
		    $file_folder_id = isset($_REQUEST['file_folder_id']) ? (int) $_REQUEST['file_folder_id'] : 1 ;
		    $this->assign('file_folder_id',$file_folder_id);
		    $this->assign('all_files', $files->get_files_by_folder($file_folder_id, 
		                                                            $_SESSION['files_filter_by']));
		    $this->assign('all_folders', $folders->get_sub_folders($file_folder_id));
		    $this->assign('folder_path',$folders->get_breadcrumb($file_folder_id));
		    $this->assign('redirect','browse');		    
		    
		}
        
		
		function add()
		{
		    if ( $_POST['action'] == 'add_file' && has_access_to('Files::Upload Files') )
		    {
		        $files =& new Files();
		        if ( $files->update_fields($_POST['files']) )
		        {
		            flash('notice','File Uploaded');
		        } else {
		            $errors = implode('<br>',$files->get_errors_on('File'));
		            flash('error','Error: '.$errors);
		        }
		    }
		    
		    if ( $_POST['action'] == 'add_folder' && has_access_to('Files::Create Folders') )
		    {
		        $folders =& new File_Folders();
		        if ( $folders->update_fields($_POST['folders']) )
		        {
		            flash('notice','Folder Created');
		        } else {
		            $errors = implode('<br>',$folders->get_errors_on('name'));
		            flash('error','Error: '.$errors);
		        }
		    }
		    $redirect = isset($_POST['redirect']) ? htmlspecialchars($_POST['redirect']) : 'index';
		    $this->redirect_to(array('controller'=>'admin/files' ,
		                            'action'=>$redirect.'?file_folder_id='.$_POST['file_folder_id']));
		}
		
		function delete()
		{
		    if ( $_POST['action'] == 'delete_file' && has_access_to('Files::Delete Files') )
		    {
		        $files =& new Files();
		        if ( $files->delete_file($_POST['id']) )
		        {
		            flash('notice','File Deleted');
		        }
		    }
		    
		    if ( $_POST['action'] == 'delete_folder' && has_access_to('Files::Delete Folders') )
		    {
		        $folders =& new File_Folders();
		        if ( $folders->delete_folder($_POST['id']) )
		        {
		            flash('notice','Folder Deleted');
		        }
		    }
		    $redirect = isset($_POST['redirect']) ? $_POST['redirect'] : 'index';
		    $this->redirect_to(array('controller'=>'admin/files' ,
		                        'action'=>$redirect.'?file_folder_id='.$_POST['file_folder_id']));
		}

        function file_types()
        {
            if ( !has_access_to('Files::Modify File Types') )
            {
                flash('notice','You do not have access to modify file types');
                $this->redirect_to('index');
            }
            
            $types = new File_Types();
            $this->assign_ref('types',$types);
            if ( $this->is_post() 
                && $_POST['action'] == 'add_file_type' )
            {
                if ( $types->update_fields($_POST['types']) )
                {
                    if ($this->is_ajax_request()) {
                        $this->assign('type',$types->fields);
                        $this->render(array('partial'=>'_list.php'));
                        return;
                    }
                    flash('notice','File Type Added');
                } else {
                    if ($this->is_ajax_request()) {
                        $this->assign('error',$types->errors_to_string());
                        $this->render(array('partial'=>'_error.php'));
                        return;
                    }
                }
            }
            $this->assign('all_types',$types->get_allowed_types());
        }
        
        
        function delete_file_type()
        {
            if ( !has_access_to('Files::Modify File Types') )
            {
                $this->redirect_to('index');
            }
            if ( $_POST['action'] == 'delete_file_type' )
            {
                $types = new File_Types();
                $id    = (int) $_POST['id'];
                if ( $types->load($id) )
                {
                    $types->delete();
                    flash('notice','File Type Deleted');
                }
            }
            $this->redirect_to('file_types');
        }
        
        function crop_image()
        {   
            // load the file
            $files = new files();
            if ($this->is_get() && !$files->load((int) $_GET['id'])) 
            {
                $this->redirect_crop_error('File could not be loaded.', $file_folder_id);
            }
            
            if ($this->is_post() && !$files->load((int) $_POST['id'])) {
                $this->redirect_crop_error('File could not be loaded.', $file_folder_id);
            }
            // if the file is not an image type, redirect to index
            $mime_type = $files->get('type');
            if ( !preg_match("!^image/!i",$mime_type) )
            {
                $this->redirect_crop_error('Sorry, you can only crop image files.', $file_folder_id);
            }
            
            // path to file will return with a / in the front fyi
            $file_folders = new File_Folders();
            $path_to_file = path_to_file($files->get('file_folder_id'));  
            $server_path_to_file = $file_folders->get_server_path($files->get('file_folder_id'));

            // template stuff			
            $file_folder_id = (int) $_REQUEST['file_folder_id'];
            $this->assign('server_path_to_file',$server_path_to_file);
            $this->assign('image',$files->fields);
            $this->assign('file_folder_id', $file_folder_id);
            $this->assign('public_path_to_file', $path_to_file);
            
            // ok time to process the requested dimensions
            if ( $this->is_post() && isset($_POST['modify_image']) )
            {            
                
                switch($_POST['action']){                    
                    case 'crop':       
                        $worked = $files->crop_image($_POST);
                        break;                    
                    case 'resize':
                        $worked = $files->resize_image($_POST);
                        break;
                }
                
                if ( $worked )
                {
                    flash('notice', 'Image saved');
                } else {
                    flash('error','Modification of image failed.'.$files->errors_to_string() );
                }
                
                header('Expires: Mon, 26 Jul 1997 05:00:00 GMT') ;
                // always modified
                header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT') ;
                // HTTP/1.1
                header('Cache-Control: no-store, no-cache, must-revalidate') ;
                header('Cache-Control: post-check=0, pre-check=0', false) ;
                // HTTP/1.0
                header('Pragma: no-cache') ;                
    		    $this->redirect_to(array('controller'=>'admin/files' ,
    		                            'action'=>'index?file_folder_id='.$file_folder_id));
            }            
        }
        
        function redirect_crop_error($msg,$file_folder_id=0)
        {
            flash('error',$msg);
            $this->redirect_to('index?'.$file_folder_id);
        }
        
        function modify()
        {
            use_model('files');
            $files = new Files();
            if ($files->load((int) $_POST['id'])) {
                $files->set('description', $_POST['description']);
                $files->save(true);
                flash('notice','File saved');
                $this->redirect_to('index');
            }
        }
    }

?>